package com.atguigu.usercenterservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.commonutils.Vo.UcenterMemberVo;
import com.atguigu.commonutils.utils.JwtUtils;
import com.atguigu.usercenterservice.entity.UcenterMember;
import com.atguigu.usercenterservice.entity.Vo.LoginVo;
import com.atguigu.usercenterservice.entity.Vo.RegisterVo;
import com.atguigu.usercenterservice.service.UcenterMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户中心 前端控制器
 * </p>
 *
 * @author kaixuan
 * @since 2020-06-10
 */
@Api(description = "用户中心服务")
@RestController
@RequestMapping("/ucenterservice/ucenter")
//@CrossOrigin
public class UcenterMemberController {

    @Autowired
    private UcenterMemberService ucenterService;

    /**
     * 用户登陆
     * @param loginVo
     * @return
     */
    @ApiOperation("用户登陆")
    @PostMapping("login")
    public R login(@RequestBody LoginVo loginVo){
        String token = ucenterService.login(loginVo);
        return R.ok().data("token",token);
    }

    /**
     * 用户注册
     * @param registerVo
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("register")
    public R register(@RequestBody RegisterVo registerVo){
        ucenterService.register(registerVo);
        return R.ok();
    }

    /**
     * 根据token查询用户信息
     * @param request
     * @return
     */
    @ApiOperation("根据token查询用户信息")
    @GetMapping("auth")
    public R getUser(HttpServletRequest request){
        //检验token
        boolean flag = JwtUtils.checkToken(request);
        if (!flag){
            return R.error();
        }
        //根据token获取会员id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        UcenterMember user = ucenterService.getById(memberId);
        return R.ok().data("user",user);
    }

    @GetMapping("authVo/{memberId}")
    public UcenterMemberVo getMemberInfo(@ApiParam(value = "用户id",name = "memberId",required = true) @PathVariable String memberId){
        UcenterMember member = ucenterService.getById(memberId);
        UcenterMemberVo ucenterMemberVo = new UcenterMemberVo();
        BeanUtils.copyProperties(member,ucenterMemberVo);
        return ucenterMemberVo;
    }

    /**
     * 统计某一天的注册人数
     * @param day
     * @return
     */
    @GetMapping("registerCount/{day}")
    public R registerCount(@ApiParam(name = "day",value = "日期",required = true)@PathVariable String day){
        Integer row = ucenterService.selectRegisterCount(day);
        return R.ok().data("row",row);
    }
}

